package com.leo.chapter14;

import java.nio.BufferOverflowException;

/**
 * 不满足前提条件时，直接报错
 * @author xuexiaolei
 * @version 2017年10月20日
 */
public class GrumpyBoundedBuffer<V> extends BaseBoundedBuffer<V> {
    protected GrumpyBoundedBuffer(int capacity) {
        super(capacity);
    }

    @Override public synchronized void put(V v) {
        if (isFull()){
            throw new BufferOverflowException();
        }
        doPut(v);
    }

    @Override public synchronized V take() {
        if (isEmpty()){
            throw new BufferOverflowException();
        }
        return doTake();
    }

    /**
     * 演示如何调用,必须得自己使用while并且处理异常
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {
        GrumpyBoundedBuffer<Integer> buffer = new GrumpyBoundedBuffer<>(10);
        while (true){
            try {
                Integer item = buffer.take();
                System.out.println(item);
                break;
            } catch (BufferOverflowException e){
                Thread.sleep(10);
            }
        }
    }
}
